package com.porinkey.geotan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private int REQUEST_GALLERY = 30;
	
	ListView listView;
	GeoTag geo;
	static List<MapSmallRow> dataList = new ArrayList<MapSmallRow>();
	static listAdapter adapter;

	DisplayMetrics metrics;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		listView = (ListView) findViewById(R.id.mapListView);
		geo = new GeoTag(this);
		setAdapters();
		
		Display display = getWindowManager().getDefaultDisplay();
		metrics = new DisplayMetrics();
		display.getMetrics(metrics);

		
		
		Button btn = (Button) findViewById(R.id.btnImageSelect);
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				startActivityForResult(intent, REQUEST_GALLERY);
			}
		});

		
	}
	
	protected void setAdapters(){
		adapter = new listAdapter();
		listView.setAdapter(adapter);
	}

	protected void addItem(Uri contentUri){
		String path = getRealPathFromURI(contentUri);
		MapSmallRow mpr = new MapSmallRow(path);
		mpr.setDisplayMetrix(metrics);
		Log.d("geotan", "addItem");
		
		dataList.add(mpr);
		adapter.notifyDataSetChanged();
	}

	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
			try {
				addItem(data.getData());
			} catch (Exception e) {
				Log.d("geotan", e.getMessage());
			}
				
		}
	}
	
	
	public String getRealPathFromURI(Uri contentUri) {
	    String res = null;
	    String[] proj = { MediaStore.Images.Media.DATA };
	    Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
	    if(cursor.moveToFirst()){;
	       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	       res = cursor.getString(column_index);
	    }
	    cursor.close();
	    return res;
	}
	
	private void GeoTagLer(Uri uri){
		
		try {
			
			Log.d("geotan", "1");
			String path = getRealPathFromURI(uri);
			Log.d("geotan", "2");
			ExifInterface ex = new ExifInterface(path);
			float[] latLong = new float[2];
			
			Log.d("geotan", "3");
			ex.getLatLong(latLong);         
			
			double lat = latLong[0];
			double lng = latLong[1];
			
			Geocoder geo = new Geocoder(this, Locale.JAPAN);
			
			if(Geocoder.isPresent())
			{
				Log.d("GeoTagLer", "True");
			}
			else
			{
				Log.d("GeoTagLer", "False");
			}
			Log.d("GeoTagLer", "4");
			Log.d("GeoTagLer", lat + "");
			Log.d("GeoTagLer", lng + "");
			List<Address> addresses = geo.getFromLocation(lat, lng, 5);
			
			Log.d("GeoTagLer", "5");
			
			Log.d("GeoTagLer", addresses.size() + "");
			//txt.setText(addresses.size());
			
			Log.d("GeoTagLer", "7");
			if(addresses.size() > 0)
			{
				
				Log.d("GeoTagLer", "8");
				Address ad = addresses.get(0);
				String address = ad.getCountryName() + ad.getAdminArea() + ad.getLocality() + ad.getSubAdminArea() + ad.getFeatureName() + ad.getThoroughfare();
				Toast.makeText(this, address, Toast.LENGTH_LONG).show();
			}
			
			Log.d("GeoTagLer", "20");
			
			
//			exifStr[0] = "latLong = " + String.valueOf(latLong[0]) + ", "+ String.valueOf(latLong[1]);
//			exifStr[1] = "TAG_GPS_ALTITUDE = " + ex.getAttribute(ExifInterface.TAG_GPS_ALTITUDE);
//			exifStr[2] = "TAG_GPS_LATITUDE = " + ex.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
//			exifStr[3] = "TAG_DATETIME = " + ex.getAttribute(ExifInterface.TAG_DATETIME);
//			exifStr[4] = "TAG_GPS_LONGITUDE = " + ex.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
//			exifStr[5] = "TAG_IMAGE_LENGTH = " + ex.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
//			exifStr[6] = "TAG_IMAGE_WIDTH = " + ex.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
//			exifStr[7] = "TAG_ORIENTATION = " + ex.getAttribute(ExifInterface.TAG_ORIENTATION);
//			exifStr[8] = "TAG_WHITE_BALANCE = " + ex.getAttribute(ExifInterface.TAG_WHITE_BALANCE);
//			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
			Log.d("err", e.getMessage());
			e.printStackTrace();
		}
	}
	
	public Bitmap decodeLargeFile(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		int scaleW = options.outWidth / 380 + 1;
		int scaleH = options.outHeight / 420 + 1;

		int scale = Math.max(scaleW, scaleH);

		options.inJustDecodeBounds = false;
		options.inSampleSize = scale;

		return BitmapFactory.decodeFile(path, options);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	private class listAdapter extends BaseAdapter {
	    
	    @Override
	    public int getCount() {
	      return dataList.size();
	    }

	    @Override
	    public Object getItem(int position) {
	      return dataList.get(position);
	    }

	    @Override
	    public long getItemId(int position) {
	      return position;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {

	      TextView img_url;
	      TextView saddress;
	      TextView picdate;
	      ImageView miniImg;
	      View v = convertView;

	      if(v==null){
	        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        v = inflater.inflate(R.layout.listrow, null);
	      }
	      MapSmallRow mapr = (MapSmallRow)getItem(position);
	      if(mapr != null){
	    	img_url = (TextView) v.findViewById(R.id.view_url);
	    	saddress = (TextView) v.findViewById(R.id.saddress);
	    	picdate = (TextView) v.findViewById(R.id.pic_date);
	    	miniImg = (ImageView) v.findViewById(R.id.pic);
	        
	    	img_url.setText(mapr.getPath());
	    	
	    	Bitmap img = mapr.getSmallImage();
	    	miniImg.setImageBitmap(img);

	    	geo.setPath(mapr.getPath());
	    	saddress.setText(geo.getAddress());
	    	picdate.setText(geo.getDateTime());
	        
	      }
	      return v;
	    }
	
	}
}
